import React, { Component } from 'react'
import SearchForm from './SearchForm';
import UploadLink from './UploadLink';
import Resource from '@/components/Resource';
import { checkInit } from '@/utils/util';
import Link from 'umi/link';
import { connect } from 'dva'
import { Table, Divider, Popconfirm, Form, Input, DatePicker, Button } from 'antd';
import moment from 'moment'
export interface IProps {
  form: any,
  loading: boolean,
  dispatch?: Function,
  children?: React.ReactNode,
  buttons?: Array<any>,
  list: {
    data: Array<any>,
    dataCnt: number
  },
  documentCond?: {
    pageSize: number,
  },
  editingKey: string
}

interface CellProps {
  inputType: string,
  editing: boolean,
  dataIndex: string,
  attach: string,
  record: {},
  index: string
}


interface ApprovalDocuments {
  columns: any
}


const ONE_PAGE_SIZE = 10;
const EditableContext = React.createContext({});


class EditableCell extends React.Component<CellProps> {
  getInput = () => {
    if (this.props.inputType === 'pdf') {
      return <UploadLink />
      // return <TestC />
      // return <div>watting</div>
    }
    return <Input />;
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      attach,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;

    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0 }}>
            {
              inputType === 'datePicker' ?
                getFieldDecorator(dataIndex, {
                  initialValue: record[dataIndex] ? moment(record[dataIndex]) : null
                })(<DatePicker
                  showTime
                  // {...getFieldDecorator(dataIndex)}
                  format={'YYYY-MM-DD'}
                  style={{ width: '100%' }}
                  placeholder="请选择"
                // onChange={(v) => this.handleChangeTime(v)}
                />) :

                getFieldDecorator(dataIndex,
                  {
                    initialValue: record[dataIndex],
                  }
                )(this.getInput())
            }

          </Form.Item>
        ) : (
            children
          )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

@connect(({ archives_unit, loading }) => ({
  list: archives_unit.list || {},
  editingKey: archives_unit.editingKey,
  loading: loading.effects['archives_unit/queryDocumentPage'],
  documentCond: archives_unit.documentCond
}))
class ApprovalDocuments extends Component<IProps, any> {


  constructor(props) {
    super(props)

    this.state = {
      current: 1,
      editingKey: '',
    }

    this.columns = [{
      title: '项目内容',
      dataIndex: 'content',
      editable: true
    }, {
      title: '文书(证书)名称',
      dataIndex: 'name',
      editable: true
    }, {
      title: '编号(文号)',
      dataIndex: 'certificateNo',
      editable: true
    }, {
      title: '审批时间',
      dataIndex: 'auditTime',
      editable: true
    }, {
      title: '附件',
      dataIndex: 'url',
      editable: true,
      render: (text, record) => {
        return <>
          {record.fileUrl ? <Resource fileName="审批文件" /> : null}
        </>
      }
    }, {
      title: '操作',
      render: (text, record) => {
        const { editingKey } = this.props;
        const editable = this.isEditing(record);
        return editable ? (
          <span>
            <EditableContext.Consumer>
              {form => (
                <a
                  //   href="javascript:;"
                  onClick={() => this.save(form, record.id)}
                  style={{ marginRight: 8 }}
                >
                  保存
                        </a>
              )}
            </EditableContext.Consumer>
            <a
              onClick={() => this.cancel(record.id)}
            >取消</a>
          </span>
        ) : (
            <a
              disabled={editingKey !== ''}
              onClick={() => this.edit(record.id, record)}>
              编辑
                  </a>
          );
      },
    }];
  }

  /** 可编辑cell的交互 */
  save(form, key) {

    let { dispatch } = this.props;
    dispatch({
      type: 'archives_unit/saveDPage'
    }).then(res => {
      if (res = true) {
        this.initCurrent();
      }
    });
  }

  edit(key, record) {
    let { dispatch } = this.props;
    dispatch({
      type: 'archives_unit/editDocument',
      payload: {
        key,
        data: record
      }
    })
  }

  cancel = () => {
    let { dispatch } = this.props;
    dispatch({
      type: 'archives_unit/cancelEdit'
    });
  };

  add = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'archives_unit/addNewRow'
    });
    return;
  }


  /** 数据请求 */
  queryData = (offset = 1, size = ONE_PAGE_SIZE) => {
    const { dispatch } = this.props;

    dispatch({
      type: 'archives_unit/queryDocumentPage',
      payload: {
        // pageSize: size,
        pageNum: offset,
      },
    });
  }

  onShowSizeChange = (current, pageSize) => {
    const { dispatch, documentCond } = this.props;
    documentCond.pageSize = pageSize;
    this.setState({ current: 1 }, () => {
      dispatch({
        type: 'archives_unit/updateDocumentCond',
        payload: documentCond
      })
    })

  }

  initCurrent = () => {
    this.setState({
      current: 1
    })
  };


  remove = (id: string) => {
    // const { dispatch } = this.props;
    // this.setState({
    //   current: 1
    // }, () => {
    //   dispatch({
    //     type: 'fireroom/remove',
    //     payload: id
    //   })
    // })
  }

  isEditing = record => record.id === this.props.editingKey;

  componentDidMount() {
    const { dispatch } = this.props;
    this.queryData();
    // checkInit() ? dispatch({ type: `fireroom/initCond` }) : this.queryData({ pageNum: 1 });
  }


  render() {
    const components = {
      body: {
        cell: EditableCell,
      },
    };

    const { data = [], dataCnt } = this.props.list;
    // let data = this.state.data;
    // const { list={} } = this.props;
    // const { data = [], dataCnt } = list;

    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      showSizeChanger: true,
      current: this.state.current,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      onChange: (current) => {
        this.setState({
          current,
          isChangePage: true
        }, () => {
          this.cancel();
          this.queryData(current);
        });
      },
    };

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      let inputType = 'text';
      if (col.dataIndex === 'auditTime') {
        inputType = 'datePicker'
      } else if (col.dataIndex === 'url') {
        inputType = 'pdf'
      }
      return {
        ...col,
        onCell: record => {
          // record.auditTime = record.auditTime ? record.auditTime.split(' ')[0] : record.auditTime;
          return {
            record,
            inputType,
            dataIndex: col.dataIndex,
            title: col.title,
            editing: this.isEditing(record),
          }
        },
      };
    });
    return (
      <>
        <SearchForm new onAdd={this.add} />
        <EditableContext.Provider value={this.props.form}>
          <Table
            components={components}
            rowClassName="editable-row"
            columns={columns}
            pagination={pagination}
            dataSource={data}
            loading={this.props.loading}
            rowKey="id"
            bordered
          />
        </EditableContext.Provider>
      </>
    )
  }
}

const EditableApprovalDocuments = connect()(Form.create({
  onFieldsChange(props, fields) {

    props.form.validateFields((error, row) => {
      if (error) {
        return;
      }
      let auditTime = row.auditTime ? moment(row.auditTime).format("YYYY-MM-DD") : null;

      props.dispatch({

        type: 'archives_unit/updateDPageCommitData',
        payload: {
          ...row,
          auditTime
        },
      })
    });

  },
})(ApprovalDocuments));
export default EditableApprovalDocuments
